package logic

import (
	"context"
	"errors"
	"fmt"
	"github.com/google/uuid"
	"order_srv/internal/svc"
	"order_srv/models/mysql"
	"order_srv/models/redis"
	"order_srv/order"

	"github.com/zeromicro/go-zero/core/logx"
)

type AddOrdersLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewAddOrdersLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddOrdersLogic {
	return &AddOrdersLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *AddOrdersLogic) AddOrders(in *order.AddOrdersRequest) (*order.AddOrdersResponse, error) {
	// todo: add your logic here and delete this line

	g := mysql.Goods{}
	err := g.Show(int(in.GoodsId))
	if err != nil {
		return nil, errors.New("商品不存在")
	}
	stock := redis.GetGoodsStock(int(in.GoodsId))
	if stock < int64(in.Quantity) {
		return nil, errors.New("库存不足")
	}
	orderSn := uuid.NewString()
	amount := g.Price * float64(in.Quantity)
	o := mysql.Order{
		UserId:  int(in.UserId),
		OrderSn: orderSn,
		Status:  int(in.Status),
		PayType: int(in.PayType),
		PayTime: int(in.PayTime),
		Total:   amount,
		Remark:  in.Remark,
	}
	err = o.Create()
	if err != nil {
		return nil, errors.New("订单添加失败")
	}
	fmt.Println(err)

	og := mysql.Order_Goods{
		UserId:   int(in.UserId),
		GoodsId:  int(in.GoodsId),
		OrderId:  int(o.ID),
		Name:     g.Name,
		Price:    g.Price,
		GoodsNum: g.Stock,
	}
	err = og.Create()
	if err != nil {
		return nil, errors.New("订单商品表添加失败")
	}
	fmt.Println(err)
	//删除虚拟库存
	redis.DecrGoodsStock(int(in.GoodsId), int(in.Quantity))
	return &order.AddOrdersResponse{Id: int32(o.ID)}, nil
}
